package cn.pupil.springframework.aop.framework.autoproxy;

import cn.pupil.springframework.aop.*;
import cn.pupil.springframework.aop.aspectj.AspectJExpressionPointcutAdvisor;
import cn.pupil.springframework.aop.framework.ProxyFactory;
import cn.pupil.springframework.beans.BeansException;
import cn.pupil.springframework.beans.PropertyValues;
import cn.pupil.springframework.beans.factory.BeanFactory;
import cn.pupil.springframework.beans.factory.BeanFactoryAware;
import cn.pupil.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import cn.pupil.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.aopalliance.aop.Advice;
import org.aopalliance.intercept.MethodInterceptor;

import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * @Description: 融入Bean生命周期的自动代理创建处理器
 * @Author: pupil
 * @Date: 2024/11/21 下午 5:15
 */
public class DefaultAdvisorAutoProxyCreator implements InstantiationAwareBeanPostProcessor, BeanFactoryAware {

    private DefaultListableBeanFactory beanFactory;

    /**
     * 存放提前暴露的代理对象引用
     */
    private final Set<Object> earlyProxyReferences = Collections.synchronizedSet(new HashSet<Object>());

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = (DefaultListableBeanFactory) beanFactory;
    }

    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
        return null;
    }

    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        return true;
    }

    @Override
    public PropertyValues postProcessPropertyValues(PropertyValues pvs, Object bean, String beanName) throws BeansException {
        return pvs;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    /**
     * 判断 beanClass 是否实现或者为Spring AOP的基础设施类（如Advice、Pointcut、Advisor等）
     *
     * @param beanClass
     * @return Spring AOP的基础设施类 返回 true，否则返回 false
     */
    private boolean isInfrastructureClass(Class<?> beanClass) {
        return Advice.class.isAssignableFrom(beanClass) || Pointcut.class.isAssignableFrom(beanClass) || Advisor.class.isAssignableFrom(beanClass);
    }

    // BeanPostProcessor 的 postProcessAfterInitialization
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (!earlyProxyReferences.contains(beanName)) {
            return wrapIfNecessary(bean, beanName);
        }
        return bean;
    }

    protected Object wrapIfNecessary(Object bean, String beanName) {
        // 判断 beanClass 是否实现或者为Spring AOP的基础设施类，是则不进行后续处理，正常实例化该bean
        if (isInfrastructureClass(bean.getClass())) return bean;

        // 获取切面通知器集合
        Collection<AspectJExpressionPointcutAdvisor> advisors = beanFactory.getBeansOfType(AspectJExpressionPointcutAdvisor.class).values();

        for (AspectJExpressionPointcutAdvisor advisor : advisors) {
            // 匹配 beanClass 的切面通知器
            ClassFilter classFilter = advisor.getPointcut().getClassFilter();
            // 过滤匹配类, 判断 beanClass 是否匹配该通知器的切入表达式
            if (!classFilter.matches(bean.getClass())) continue;

            AdvisedSupport advisedSupport = new AdvisedSupport();

            TargetSource targetSource = new TargetSource(bean);

            // 封装切面信息
            advisedSupport.setTargetSource(targetSource);
            advisedSupport.setMethodInterceptor((MethodInterceptor) advisor.getAdvice());
            advisedSupport.setMethodMatcher(advisor.getPointcut().getMethodMatcher());
            advisedSupport.setProxyTargetClass(true);

            // 返回 通过代理工厂创建的实例化对象
            return new ProxyFactory(advisedSupport).getProxy();
        }

        return bean;
    }

    @Override
    public Object getEarlyBeanReference(Object bean, String beanName) {
        earlyProxyReferences.add(beanName);
        return wrapIfNecessary(bean, beanName);
    }
}
